﻿using NetJavap.ConstantInfos;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NetJavap.AttributeInfos
{
    public class ExceptionsAttributeInfo : AttributeInfo
    {
        private UInt16 _numbersOfExceptions;
        private UInt16[] _exceptionIndexTable;

        private ConstantClassInfo[] _exceptions;

        public ConstantClassInfo[] Exceptions
        {
            get
            {
                if (this._exceptions == null)
                {
                    List<ConstantClassInfo> exceptionList = new List<ConstantClassInfo>(this._exceptionIndexTable.Length);
                    foreach (var exceptionIndex in this._exceptionIndexTable)
                    {
                        exceptionList.Add(this.ParentClass.ConstantPool[exceptionIndex] as ConstantClassInfo);
                    }
                    this._exceptions = exceptionList.ToArray();
                }
                return this._exceptions;
            }
        }

        public ExceptionsAttributeInfo(BinaryReader reader, JavaClass cls, ClassMember defineMember)
            : base(reader, cls, defineMember)
        {
            this._numbersOfExceptions = reader.ReadUInt16BE();
            this._exceptionIndexTable = ArrayBuilder.BuildArray(() => reader.ReadUInt16BE(), this._numbersOfExceptions);
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(base.ToString());
            sb.Append(":\n   throws ");
            foreach (var exp in this.Exceptions)
            {
                sb.Append(exp.TypeInfo.ToString() + " ");
            }
            return sb.ToString();
        }
    }
}
